<?php

/**
 * Name: 员工管理控制器
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:30:00
 */

namespace App\Http\Controllers\V1\Resources\Checkin;

use App\Http\Controllers\Controller;
use App\Repositories\Config\EmployeeRepository;
use App\Repositories\Config\ConfigRepository;
use Illuminate\Http\Request;
use Exception;

class EmployeeController extends Controller
{
    protected $employeeRepository;
    protected $configRepository;

    public function __construct(
        EmployeeRepository $employeeRepository,
        ConfigRepository $configRepository
    ) {
        $this->employeeRepository = $employeeRepository;
        $this->configRepository = $configRepository;
    }

    /**
     * 获取员工列表（支持权限筛选）
     * GET /api/v1/employees/list
     */
    public function list(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $perPage = $request->input('per_page', 15);

            // 根据用户角色控制数据访问范围
            $userRole = $this->getUserRole($employee);
            $filters = $this->buildFilters($request, $userRole, $employee);

            $query = $this->employeeRepository->query();

            // 应用筛选条件
            if (isset($filters['team'])) {
                $query->where('team', $filters['team']);
            }

            if (isset($filters['position'])) {
                $query->where('position', $filters['position']);
            }

            if (isset($filters['name'])) {
                $query->where('name', 'like', '%' . $filters['name'] . '%');
            }

            // 根据用户角色限制数据范围
            if ($userRole === 'leader') {
                // 班长只能查看本班组员工
                $query->where('team', $employee->team);
            }

            $employees = $query->select('id', 'name', 'team', 'position', 'phone', 'company', 'department')
                             ->orderBy('company')
                             ->orderBy('department')
                             ->orderBy('team')
                             ->orderBy('position')
                             ->orderBy('name')
                             ->paginate($perPage);

            return $this->_success('获取成功', $employees);

        } catch (Exception $e) {
            return $this->_error('获取员工列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取班组列表
     * GET /api/v1/employees/teams
     */
    public function teams(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $userRole = $this->getUserRole($employee);

            if ($userRole === 'supervisor') {
                // 主管可以查看所有班组
                $teams = $this->configRepository->getByKeys('team');
            } elseif ($userRole === 'leader') {
                // 班长只能查看自己的班组
                $teams = [
                    [
                        'id' => $employee->team,
                        'name' => $employee->team,
                        'value' => $employee->team
                    ]
                ];
            } else {
                // 普通员工只能查看自己的班组
                $teams = [
                    [
                        'id' => $employee->team,
                        'name' => $employee->team,
                        'value' => $employee->team
                    ]
                ];
            }

            return $this->_success('获取成功', $teams);

        } catch (Exception $e) {
            return $this->_error('获取班组列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取职位列表
     * GET /api/v1/employees/positions
     */
    public function positions(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $userRole = $this->getUserRole($employee);

            if ($userRole === 'supervisor') {
                // 主管可以查看所有职位
                $positions = $this->configRepository->getByKeys('position');
            } else {
                // 其他角色查看有限的职位
                $positions = $this->getFilteredPositions($userRole);
            }

            return $this->_success('获取成功', $positions);

        } catch (Exception $e) {
            return $this->_error('获取职位列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取当前用户信息和权限
     * GET /api/v1/employees/profile
     */
    public function profile(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $userRole = $this->getUserRole($employee);
            $permissions = $this->getUserPermissions($employee, $userRole);

            $profileData = [
                'id' => $employee->id,
                'name' => $employee->name,
                'username' => $employee->username,
                'phone' => $employee->phone,
                'email' => $employee->email,
                'team' => $employee->team,
                'position' => $employee->position,
                'company' => $employee->company ?? '',
                'department' => $employee->department ?? '',
                'user_role' => $userRole,
                'permissions' => $permissions,
                'wechat_bound' => !empty($employee->wechat_user_id)
            ];

            return $this->_success('获取成功', $profileData);

        } catch (Exception $e) {
            return $this->_error('获取用户信息失败：' . $e->getMessage());
        }
    }

    /**
     * 按班组获取员工列表
     * GET /api/v1/employees/by-team
     */
    public function byTeam(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $teamName = $request->input('team_name');
            $userRole = $this->getUserRole($employee);

            // 权限检查
            if ($userRole === 'leader' && $employee->team !== $teamName) {
                return $this->_error('您只能查看本班组的员工信息');
            }

            if ($userRole === 'employee') {
                return $this->_error('您没有权限查看其他员工信息');
            }

            if (empty($teamName)) {
                return $this->_error('班组名称不能为空');
            }

            $employees = $this->employeeRepository->query()
                ->where('team', $teamName)
                ->select('id', 'name', 'position', 'phone', 'company', 'department')
                ->orderBy('position')
                ->orderBy('name')
                ->get();

            return $this->_success('获取成功', $employees);

        } catch (Exception $e) {
            return $this->_error('获取班组员工失败：' . $e->getMessage());
        }
    }

    /**
     * 按职位获取员工列表
     * GET /api/v1/employees/by-position
     */
    public function byPosition(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $position = $request->input('position');

            // 只有主管可以按职位查看员工
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限按职位查看员工');
            }

            if (empty($position)) {
                return $this->_error('职位不能为空');
            }

            $employees = $this->employeeRepository->query()
                ->where('position', $position)
                ->select('id', 'name', 'team', 'phone', 'company', 'department')
                ->orderBy('company')
                ->orderBy('department')
                ->orderBy('team')
                ->orderBy('name')
                ->get();

            return $this->_success('获取成功', $employees);

        } catch (Exception $e) {
            return $this->_error('获取职位员工失败：' . $e->getMessage());
        }
    }

    /**
     * 搜索员工
     * GET /api/v1/employees/search
     */
    public function search(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $keyword = $request->input('keyword');
            $userRole = $this->getUserRole($employee);

            if (empty($keyword)) {
                return $this->_error('搜索关键词不能为空');
            }

            $query = $this->employeeRepository->query();

            // 根据用户角色限制搜索范围
            if ($userRole === 'leader') {
                $query->where('team', $employee->team);
            } elseif ($userRole === 'employee') {
                return $this->_error('您没有权限搜索其他员工');
            }

            $employees = $query->where(function($q) use ($keyword) {
                    $q->where('name', 'like', '%' . $keyword . '%')
                      ->orWhere('username', 'like', '%' . $keyword . '%')
                      ->orWhere('phone', 'like', '%' . $keyword . '%');
                })
                ->select('id', 'name', 'username', 'team', 'position', 'phone', 'company', 'department')
                ->orderBy('company')
                ->orderBy('department')
                ->orderBy('team')
                ->orderBy('name')
                ->limit(20)
                ->get();

            return $this->_success('搜索成功', $employees);

        } catch (Exception $e) {
            return $this->_error('搜索员工失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户角色
     */
    private function getUserRole($employee)
    {
        $position = $employee->position;

        if (in_array($position, ['主管', '部长', '经理'])) {
            return 'supervisor';
        } elseif (in_array($position, ['班长', '组长'])) {
            return 'leader';
        } else {
            // 副班长及其他职位都是普通员工权限
            return 'employee';
        }
    }

    /**
     * 检查是否为主管
     */
    private function isSupervisor($employee)
    {
        $position = strtolower($employee->position);
        return in_array($position, ['主管', '部长', '经理', '副主管', '副部长']);
    }

    /**
     * 获取用户权限
     */
    private function getUserPermissions($employee, $userRole)
    {
        $permissions = [
            'can_view_all_employees' => $userRole === 'supervisor',
            'can_view_team_employees' => in_array($userRole, ['supervisor', 'leader']),
            'can_manage_duty' => $userRole === 'supervisor',
            'can_review_checkin' => in_array($userRole, ['supervisor', 'leader']),
            'can_view_statistics' => $userRole === 'supervisor',
        ];

        return $permissions;
    }

    /**
     * 构建筛选条件
     */
    private function buildFilters($request, $userRole, $employee)
    {
        $filters = [];

        if ($request->has('team') && $userRole === 'supervisor') {
            $filters['team'] = $request->input('team');
        }

        if ($request->has('position')) {
            $filters['position'] = $request->input('position');
        }

        if ($request->has('name')) {
            $filters['name'] = $request->input('name');
        }

        return $filters;
    }

    /**
     * 获取过滤后的职位列表
     */
    private function getFilteredPositions($userRole)
    {
        $basePositions = [
            ['id' => '员工', 'name' => '员工', 'value' => '员工'],
            ['id' => '班长', 'name' => '班长', 'value' => '班长'],
            ['id' => '组长', 'name' => '组长', 'value' => '组长'],
        ];

        if ($userRole === 'leader') {
            $basePositions[] = ['id' => '副班长', 'name' => '副班长', 'value' => '副班长'];
        }

        return $basePositions;
    }
}
